package com.dragon.modules.yuegou.service.impl.merchant;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dragon.common.exception.DragonException;
import com.dragon.modules.yuegou.entity.merchant.GroupEntity;
import com.dragon.modules.yuegou.entity.merchant.GroupUseRefEntity;
import com.dragon.modules.yuegou.entity.merchant.UserEntity;
import com.dragon.modules.yuegou.enums.code.MerchantCode;
import com.dragon.modules.yuegou.mapper.merchant.GroupUseRefMapper;
import com.dragon.modules.yuegou.model.merchant.GroupUseRef;
import com.dragon.modules.yuegou.query.merchant.GroupUseRefQuery;
import com.dragon.modules.yuegou.service.merchant.GroupService;
import com.dragon.modules.yuegou.service.merchant.GroupUseRefService;
import com.dragon.modules.yuegou.service.merchant.UserService;
import com.dragon.modules.yuegou.web.Check;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Objects;

/**
 * 用户与商户分组关联表 服务实现
 *
 * @author pbuilder generated
 * @date 2019-03-27 10:59:02
 * @version 2.0
 */
@Slf4j
@Service("merGroupUseRefService")
public class GroupUseRefServiceImpl
		extends ServiceImpl<GroupUseRefMapper, GroupUseRefEntity>
		implements GroupUseRefService {

    @Autowired
    private GroupService groupService;

    @Autowired
    private UserService userService;

	@Transactional
	@Override
	public void saveMerchantGroupUser(String userId, String groupId) {
		Check.notNull(userId,"用户id不能为空");
		Check.notNull(groupId,"分组id不能为空");
		GroupUseRefQuery query = new GroupUseRefQuery();
		query.setGroupId(groupId);
        GroupEntity byId = groupService.getById(groupId);
        UserEntity user = userService.getById(userId);
        if (Objects.isNull(byId)||Objects.isNull(user)) {
			throw new DragonException(MerchantCode.DISTRIBUTION_PERSONNEL_DO_NOT_EXIST);
		}
		log.info("保存商户分组分配人员，开始==，用户id={},分组id={}",userId, groupId);
		//删除该分组之前的用户

		remove(query.toQueryWrapper());
		//保存分组用户
		GroupUseRef groupUseRef = new GroupUseRef();
		groupUseRef.setDel(false);
		groupUseRef.setUserId(userId);
		groupUseRef.setGroupId(groupId);
		save(groupUseRef);
		log.info("保存商户分组分配人员，保存成功，用户id={},分组id={}",userId, groupId);
	}

	@Override
	public void setGroupUser(List<GroupUseRef> groupUseRefList, String userId){
		Check.notEmpty(userId,"用户id不能为空");
		log.info("保存用户分配商户分组，开始==，用户id={}",userId);
		//删除该用户的分组
		GroupUseRefQuery query = new GroupUseRefQuery();
		query.setUserId(userId);
		remove(query.toQueryWrapper());
		//保存用户的分组
		for(GroupUseRef groupUseRef : groupUseRefList){
			Check.notNull(groupUseRef.getGroupId(),"分组id不能为空");
			groupUseRef.setUserId(userId);
			groupUseRef.setDel(false);
			save(groupUseRef);
		}
		log.info("保存用户分配商户分组，保存成功，用户id={}",userId);
	}

}